package com.kkd.kkdapp.utils;

import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.gson.Gson;
import com.kkd.kkdapp.BaseApplication;
import com.kkd.kkdapp.http.entity.Home;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

public class SystemUtils {

	// 获取当前应用版本号
	public static String getVersionName(Context context) {

		String version = "0";
		try {
			version = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}

	// 获取当前应用版本号
	public static int getVersionCode(Context context) {

		int version = 0;
		try {
			version = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0).versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 获取手机系统SDK版本
	 * 
	 * @return 如API 17 则返回 17
	 */
	public static int getSDKVersion() {
		return android.os.Build.VERSION.SDK_INT;
	}

	/**
	 * 获取系统版本
	 * 
	 * @return 形如2.3.3
	 */
	public static String getSystemVersion() {
		return android.os.Build.VERSION.RELEASE;
	}

	// 获取屏幕宽度
	public static int getScreenWidth(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);

		int width = wm.getDefaultDisplay().getWidth();
		return width;
	}

	// 获取屏幕实际宽度
	public static int getScreenRealWidth(Context context) {
		int widthPixels;
		WindowManager w = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		Display d = w.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		d.getMetrics(metrics);
		widthPixels = metrics.widthPixels;
		if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
			try {
				widthPixels = (Integer) Display.class.getMethod("getRawWidth")
						.invoke(d);
			} catch (Exception ignored) {
			}
		} else if (Build.VERSION.SDK_INT >= 17) {
			try {
				android.graphics.Point realSize = new android.graphics.Point();
				Display.class.getMethod("getRealSize",
						android.graphics.Point.class).invoke(d, realSize);
				widthPixels = realSize.x;
			} catch (Exception ignored) {
			}
		}
		return widthPixels;
	}

	// 获取屏幕高度
	public static int getScreenHeight(Context context) {
		WindowManager wm = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);

		int Height = wm.getDefaultDisplay().getHeight();
		return Height;
	}

	// 获取屏幕高度
	public static int getScreenRealHeight(Context context) {
		int heightPixels;
		WindowManager w = (WindowManager) context
				.getSystemService(Context.WINDOW_SERVICE);
		;
		Display d = w.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		d.getMetrics(metrics);
		heightPixels = metrics.heightPixels;
		if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17) {
			try {
				heightPixels = (Integer) Display.class
						.getMethod("getRawHeight").invoke(d);
			} catch (Exception ignored) {
			}
		} else if (Build.VERSION.SDK_INT >= 17) {
			try {
				android.graphics.Point realSize = new android.graphics.Point();
				Display.class.getMethod("getRealSize",
						android.graphics.Point.class).invoke(d, realSize);
				heightPixels = realSize.y;
			} catch (Exception ignored) {
			}
		}
		return heightPixels;
	}

	/**
	 * 获取手机状态栏的高度
	 * 
	 * @param ctx
	 * @return
	 */
	public static int getStatusBarHeight(Context ctx) {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = ctx.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}

	/**
	 * 隐藏系统键盘
	 * 
	 * <br>
	 * <b>警告</b> 必须是确定键盘显示时才能调用
	 */
	public static void hideKeyBoard(Activity aty) {
		try {
			((InputMethodManager) aty
					.getSystemService(Context.INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(aty.getCurrentFocus()
							.getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			// 忽略掉，因为出异常基本等于是键盘未打开的情况
			e.printStackTrace();
		}

	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static MemoryInfo getMemoryInfo(Context context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		MemoryInfo info = new MemoryInfo();
		manager.getMemoryInfo(info);
		return info;
	}

	/**
	 * 判断当前应用程序是否后台运行
	 */
	public static boolean isBackground(Context context) {
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
				.getRunningAppProcesses();
		for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
			if (appProcess.processName.equals(context.getPackageName())) {
				if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
					// 后台运行
					return true;
				} else {
					// 前台运行
					return false;
				}
			}
		}
		return false;
	}

	/**
	 * 指定格式返回当前系统时间
	 */
	public static String getDataTime(String format) {
		SimpleDateFormat df = new SimpleDateFormat(format);
		return df.format(new Date());
	}

	/**
	 * 数字转带千分符的字符串
	 */
	public static String numberWithDelimiter(long num) {
		StringBuilder accum = new StringBuilder();
		int len = accum.append(num).length();
		if (len <= 3)
			return accum.toString(); // 如果长度小于等于3不做处理
		while ((len -= 3) > 0) { // 从个位开始倒序插入
			accum.insert(len, ",");
		}
		return accum.toString();
	}

	/**
	 * 判断是否为手机号
	 */
	public boolean isMobileNO(String mobiles) {
		Pattern p = Pattern.compile("^((1[3,4,5,7,8][0-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);

		return m.matches();
	}

	// 友盟统计 自定义事件
	public static void onEvent(String id, int value) {
		// m.put("__ct__", String.valueOf(value));
		// MobclickAgent.onEvent(context, id, m);
		MobclickAgent.onEventValue(BaseApplication.getInstance(), id,
				new HashMap<String, String>(), value);
	}

	// 计算签到天数
	public static List<Integer> signDay(int signInDays) {
		double signWeek = Math.ceil(signInDays / 7.0);
		int weekDay = (int) (signWeek * 7);
		List<Integer> dayList = new ArrayList<Integer>();
		for (int i = 6; i >= 0; i--) {
			LogUtil.e("TAG", "aa" + (weekDay - i));
			dayList.add((weekDay - i));
		}
		return dayList;
	}

	// 连续天数拼接
	public static String continuousAttendanceDays(int signDays) {
		String ssignDays = "0&0&0";
		LogUtil.e("TAG", "lenght-->" + (signDays + "").length());
		if ((signDays + "").length() == 1) {
			ssignDays = "0&0&" + signDays + "";
		} else if ((signDays + "").length() == 2) {
			LogUtil.e("TAG", "" + (signDays + "").substring(0, 1));
			ssignDays = "0&" + (signDays + "").substring(0, 1) + "&"
					+ (signDays + "").substring(1, 2);
		} else if ((signDays + "").length() == 3) {
			LogUtil.e("TAG", "第二位--->" + (signDays + "").substring(1, 2));
			ssignDays = (signDays + "").substring(0, 1) + "&"
					+ (signDays + "").substring(1, 2) + "&"
					+ (signDays + "").substring(2, 3);
		}
		return ssignDays;
	}

	public static boolean isOldUser(Context context) {
		Gson gson = new Gson();
		String cache = PreferenceUtils.getInstance().getHomeData(context);
		if (!TextUtils.isEmpty(cache)) {
			Home home = gson.fromJson(cache, Home.class);
			if (home != null && home.getData() != null)
				return home.getData().getNewHandStatus() == 1;
			else
				return false;
		} else {
			return false;
		}
	}

	public static String getPhoneIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress instanceof Inet4Address) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (Exception e) {
		}
		return "";
	}

	public static String getNetTypeName() {
		ConnectivityManager connectMgr = (ConnectivityManager) BaseApplication
				.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo info = connectMgr.getActiveNetworkInfo();
		if (info != null) {
			return info.getTypeName();
		} else {
			return "无网络";
		}
		// * NETWORK_TYPE_CDMA 网络类型为CDMA
		// * NETWORK_TYPE_EDGE 网络类型为EDGE
		// * NETWORK_TYPE_EVDO_0 网络类型为EVDO0
		// * NETWORK_TYPE_EVDO_A 网络类型为EVDOA
		// * NETWORK_TYPE_GPRS 网络类型为GPRS
		// * NETWORK_TYPE_HSDPA 网络类型为HSDPA
		// * NETWORK_TYPE_HSPA 网络类型为HSPA
		// * NETWORK_TYPE_HSUPA 网络类型为HSUPA
		// * NETWORK_TYPE_UMTS 网络类型为UMTS
	}

	// 计算字符串的字节长度
	public static float byteLenght(String str) {

		float byteLenght = 0f;

		if (!TextUtils.isEmpty(str) && str.length() > 0) {

			Pattern pNumber = Pattern.compile("[0-9]*");

			Pattern pLetter = Pattern.compile("[a-zA-Z]");

			for (int i = 0; i < str.length(); i++) {

				Matcher mNumber = pNumber.matcher(str.substring(i, i + 1));

				if (mNumber.matches()) { // 此字符串是数字

					byteLenght = byteLenght + 0.5f;

				} else { // 此字符串不是数字

					Matcher mLetter = pLetter.matcher(str.substring(i, i + 1));

					if (mLetter.matches()) { // 此字符串是字母

						byteLenght = byteLenght + 0.5f;

					} else { // 此字符串不是字母

						byteLenght = byteLenght + 1f;

					}

				}
			}

		} else {

			byteLenght = 0f;

		}

		return byteLenght;
	}

	public static String getDeviceId() {
		String m_szUniqueID = new String();  
		try {
			TelephonyManager TelephonyMgr = (TelephonyManager)BaseApplication
					.getInstance().getSystemService(Activity.TELEPHONY_SERVICE); 
			String m_szImei = TelephonyMgr.getDeviceId(); 
			
			String m_szDevIDShort = "35" + //we make this look like a valid IMEI 

			Build.BOARD.length()%10 + 
			Build.BRAND.length()%10 + 
			Build.CPU_ABI.length()%10 + 
			Build.DEVICE.length()%10 + 
			Build.DISPLAY.length()%10 + 
			Build.HOST.length()%10 + 
			Build.ID.length()%10 + 
			Build.MANUFACTURER.length()%10 + 
			Build.MODEL.length()%10 + 
			Build.PRODUCT.length()%10 + 
			Build.TAGS.length()%10 + 
			Build.TYPE.length()%10 + 
			Build.USER.length()%10 ; //13 digits
			
			String m_szAndroidID = Secure.getString(BaseApplication
					.getInstance().getContentResolver(), Secure.ANDROID_ID);
			
			WifiManager wm = (WifiManager)BaseApplication
					.getInstance().getSystemService(Context.WIFI_SERVICE); 
			String m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
			
			BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter      
			m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();      
			String m_szBTMAC = m_BluetoothAdapter.getAddress();
			
			
			String m_szLongID = m_szImei + m_szDevIDShort 
				    + m_szAndroidID+ m_szWLANMAC + m_szBTMAC;      
				// compute md5     
				 MessageDigest m = null;   
				try {
				 m = MessageDigest.getInstance("MD5");
				 } catch (NoSuchAlgorithmException e) {
				 e.printStackTrace();   
				}    
				m.update(m_szLongID.getBytes(),0,m_szLongID.length());   
				// get md5 bytes   
				byte p_md5Data[] = m.digest();   
				// create a hex string   
				 
				for (int i=0;i<p_md5Data.length;i++) {   
				     int b =  (0xFF & p_md5Data[i]);    
				// if it is a single digit, make sure it have 0 in front (proper padding)    
				    if (b <= 0xF) 
				        m_szUniqueID+="0";    
				// add number to string    
				    m_szUniqueID+=Integer.toHexString(b); 
				   }   // hex string to uppercase   
				m_szUniqueID = m_szUniqueID.toUpperCase();
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(TextUtils.isEmpty(m_szUniqueID)){
			m_szUniqueID = "kkd_abc";
		}
		return m_szUniqueID;
	}
	
	/** 
     * 强制帮用户打开GPS 
     * @param context 
     */  
    public static final void openGPS(Context context) {  
        Intent GPSIntent = new Intent();  
        GPSIntent.setClassName("com.android.settings",  
                "com.android.settings.widget.SettingsAppWidgetProvider");  
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");  
        GPSIntent.setData(Uri.parse("custom:3"));  
        try {  
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();  
        } catch (CanceledException e) {  
            e.printStackTrace();  
        }  
    }  
    
    public static String getChannel(Context context) {
		String channel = "fuwuduan_01";
		try {
			ApplicationInfo appInfo = context.getPackageManager()
					.getApplicationInfo(context.getPackageName(),
							PackageManager.GET_META_DATA);

			channel = appInfo.metaData.getString("UMENG_CHANNEL");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return channel;
	}
}
